package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.Favorite;
import com.funsport.mapper.FavoriteMapper;
import com.funsport.service.IFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务实现
 */
@Slf4j
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFavorite(Long userId, String targetType, Long targetId) {
        // 检查是否已收藏
        if (isFavorited(userId, targetType, targetId)) {
            log.warn("用户{}已收藏{}:{}", userId, targetType, targetId);
            return true;
        }
        
        // 创建收藏记录
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setTargetType(targetType);
        favorite.setTargetId(targetId);
        
        boolean result = save(favorite);
        if (result) {
            log.info("用户{}收藏{}:{}成功", userId, targetType, targetId);
        }
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFavorite(Long userId, String targetType, Long targetId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
               .eq(Favorite::getTargetType, targetType)
               .eq(Favorite::getTargetId, targetId);
        
        boolean result = remove(wrapper);
        if (result) {
            log.info("用户{}取消收藏{}:{}成功", userId, targetType, targetId);
        }
        return result;
    }
    
    @Override
    public boolean isFavorited(Long userId, String targetType, Long targetId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
               .eq(Favorite::getTargetType, targetType)
               .eq(Favorite::getTargetId, targetId);
        
        return count(wrapper) > 0;
    }
    
    @Override
    public List<Favorite> getUserFavorites(Long userId, String targetType) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
               .eq(Favorite::getTargetType, targetType)
               .orderByDesc(Favorite::getCreatedAt);
        
        return list(wrapper);
    }
    
    @Override
    public List<Long> getUserFavoriteIds(Long userId, String targetType) {
        List<Favorite> favorites = getUserFavorites(userId, targetType);
        return favorites.stream()
                       .map(Favorite::getTargetId)
                       .collect(Collectors.toList());
    }
}

